using System;
using Gj.Galaxy;
using Gj.Galaxy.Logic;
using Gj.Services;
using UnityEngine;

namespace Gj
{
    public enum ProcessKey : byte
    {
        Id,
        Detail
    }

    public class RoomPlugin : GamePlugin
    {
        private BaseGameSpace baseGameSpace;
        private BasePage Page;

        private bool start;
        private object[] startInfo;
        private bool wait;
        private object[] waitInfo;

        public void OnInit(BaseGameSpace space)
        {
            baseGameSpace = space;
            Page = space.UiSpace.Page;
            space.UiSpace.OnUiFinishEvent += () => { StatusService.single.uiFinish = true; };
            if (!RoomConnect.inRoom) return;

            space.UiSpace.Page.On(SystemEvent.RoomStart, (bool online) => { JoinGame(online); });
            // 获取所需数据
            StatusService.single.init = true;

            var param = Page.param;
            if (!param["start"].AsBool) JoinGame(param["online"].AsBool);
        }

        public void OnDestroy()
        {
        }

        public GameService[] GetRequireService()
        {
            return new GameService[] { StatusService.single };
        }

        public void OnUpdate()
        {
            if (!StatusService.single.startInitGame && wait)
            {
                RoomConnect.StartInitGame(baseGameSpace);
                StatusService.single.startInitGame = true;
                return;
            }

            if (StatusService.single.startInitGame && !StatusService.single.finishInitGame &&
                StatusService.single.dataEnd && StatusService.single.mapEnd)
            {
                RoomConnect.FinishInitGame();
                StatusService.single.finishInitGame = true;
                return;
            }

            if (wait && StatusService.single.finishInitGame && StatusService.single.sync)
            {
                RoomConnect.Process(new object[] { new[] { InfoKey.Confirm, waitInfo[(byte)ProcessKey.Id] } });
                wait = false;
                return;
            }

            if (StatusService.single.uiFinish && start && StatusService.single.readyAll)
            {
                RoomConnect.Process(new object[] { new[] { InfoKey.Confirm, startInfo[(byte)ProcessKey.Id] } });
                start = false;
            }
        }

        public void LateUpdate()
        {
        }

        public void OnProcessRoom(object[] data)
        {
            // 处理进程
            foreach (object[] detail in data)
            {
                var key = (InfoKey)detail[(byte)DetailKey.Key];
                switch (key)
                {
                    case InfoKey.MasterKey:
                        // 收到的人就是Master
                        StatusService.single.isMaster = true;
                        break;
                    case InfoKey.Wait:
                        // todo 判断info值进行回复
                        var process = (object[])detail[(byte)DetailKey.Value];
                        var info = (string)process[(byte)ProcessKey.Detail];
                        if (info == "init")
                        {
                            waitInfo = process;
                            wait = true;
                            AttrService.single.End();
                        }
                        else if (info == "start")
                        {
                            startInfo = process;
                            start = true;
                        }
                        else
                        {
                            // 上报Confirm， 或者交互上报Confirm
                            RoomConnect.Process(
                                new object[] { new[] { InfoKey.Confirm, process[(byte)ProcessKey.Id] } });
                        }

                        break;
                }
            }
        }

        public void OnFinish(object result)
        {
            Debug.LogFormat("[ SOCKET ] Game finish:{0}", result);
            Client.SetStatic(false);
            RoomConnect.LeaveGame(false, () =>
            {
                Page.Send(SystemMessage.End, Convert.ToInt32(result));
                baseGameSpace.UiSpace.EndPlay();
            });
        }

        public void OnSwitchArea()
        {
        }

        public void OnInstance(int targetIndex, byte relation, GamePlayer player, Vector3 position, bool isLocal,
            NetworkEsse master, Action<InitSyncListener> cb)
        {
        }

        public void OnDestroy(NetworkEsse instance, GamePlayer player)
        {
        }

        public void OnBroadcast(GamePlayer player, byte code, Vector3 position, StreamReader reader)
        {
        }

        public void OnEnterRoom(bool first)
        {
            var param = Page.param;
            JoinGame(param["online"].AsBool);
        }

        public void OnPlayerJoin(GamePlayer player)
        {
        }

        public void OnPlayerLeave(GamePlayer player)
        {
        }

        public void OnPlayerRejoin(GamePlayer player)
        {
        }

        public void OnFailConnect()
        {
            // 游戏中，链接失败，重新开启游戏
        }

        public void OnReady()
        {
        }

        public void OnReadyPlayer(GamePlayer player)
        {
        }

        public void OnReadyAll()
        {
            Client.SetStatic(true);
            StatusService.single.readyAll = true;
        }

        public void OnInitGame()
        {
        }

        public void OnStart()
        {
            Page.Send(SystemMessage.Start);
            baseGameSpace.UiSpace.StartPlay();
        }

        public void OnTimeMove(int startTime, int endTime, StreamReader reader, Vector3[] positions, int index,
            Vector3 middlePosition)
        {
        }

        public void OnTimeProcess(int startTime, int endTime, StreamReader reader)
        {
        }

        private void JoinGame(bool online)
        {
            if (RoomConnect.JoinGame(online, () => { StatusService.single.sync = true; }))
            {
                // 目前直接开始进入游戏
                // 直接准备
                RoomConnect.ReadyGame(baseGameSpace);
            }
            else
            {
                // 战斗内，断线重连成功，重新开始初始化游戏
                RoomConnect.StartInitGame(baseGameSpace);
                StatusService.single.startInitGame = true;
                StatusService.single.finishInitGame = false;
            }
        }
    }
}